package protocols

import (
	"fmt"
	"io"
	"os"

	"gitee.com/sjy/selfSendfile/common"
	"github.com/jlaffaye/ftp"
)

var _ SendFile = &Send_FTP{}

type Send_FTP struct {
}

type ProgressReader struct {
	reader    io.Reader // The underlying reader to read from.
	totalSize int64     // Total size of the file.
	readSoFar int64     // Number of bytes read so far.
}

func (pr *ProgressReader) Read(p []byte) (n int, err error) {
	n, err = pr.reader.Read(p)
	pr.readSoFar += int64(n)
	pr.showProgress()
	return
}

func (pr *ProgressReader) showProgress() {
	if pr.totalSize == 0 {
		fmt.Printf("\rUploading... %d bytes", pr.readSoFar)
	} else {
		percentage := float64(pr.readSoFar) / float64(pr.totalSize) * 100
		fmt.Printf("\rUploading... %d%%", int(percentage))
	}
	if pr.readSoFar >= pr.totalSize {
		fmt.Println("\nUpload complete.")
	}
}

// Send implements SendFile.
func (s *Send_FTP) Send(file *common.FileInfo, conf *common.Config) {
	if file.IsEmpty() {
		panic("SendFromPaths is empty! please check config file!")
	}

	// 创建连接
	conn := s.ftp(conf)
	defer conn.Quit()

	err := conn.Login("anonymous", "")
	if err != nil {
		panic(err)
	}

	// 上传文件
	s.sendFile(conn, file)
}

func (s *Send_FTP) ftp(conf *common.Config) *ftp.ServerConn {
	conn, err := ftp.Dial(conf.GetServerAddr())
	if err != nil {
		panic(err)
	}
	return conn
}

func (s *Send_FTP) sendFile(conn *ftp.ServerConn, file *common.FileInfo) {
	// 创建ProgressReader
	progressReader := NewProgressReader(file)

	// 上传文件
	err := conn.Stor("uploaded_example.txt", progressReader)
	if err != nil {
		panic(err)
	}
}

func NewProgressReader(fobj *common.FileInfo) *ProgressReader {

	// 打开要上传的文件
	file, err := os.Open(fobj.CurrentPath)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	// 获取文件大小
	fileInfo, err := file.Stat()
	if err != nil {
		panic(err)
	}
	totalSize := fileInfo.Size()

	return &ProgressReader{
		reader:    file,
		totalSize: totalSize,
	}
}
